<?php
/** 
 *
 * @Authors Viera Leonel, Federico González
 * @package mailing
 * @subpackage model
 *
 */
class Campaign extends Campaign_protoweb {

  public function __construct($id = NULL) {
    parent::__construct($id);
  } 

  public function generate_sends() {
    $filters = json_decode($this->filters);

    $catalogs = new Catalog();
    $catalogs->select('id')->where_related_client('id',$this->client->id)->get();

    $filters_query = '';

    foreach ($catalogs as $catalog) {
      $filters_query .= ($filters_query === '' ? 'catalog_id = ' : ' OR catalog_id = ') . $catalog->id;
    }
    
    $this->db->query("
      INSERT INTO sends (campaign_id, recipient_id, sent, tries, bounced, `read`, cleaned) (
        SELECT DISTINCT  
          {$this->id} as campaign_id, 
          recipient_id,
          0 as sent,
          0 as tries,
          0 as bounced,
          0 as `read`,
          0 as cleaned
        FROM subscribers
        INNER JOIN recipients ON subscribers.recipient_id = recipients.id 
        WHERE 
          recipients.offdate  = 0 AND 
          recipients.verified = 1 AND
          {$filters_query}
      )
    ");

  } // generate_sends()

  public function sends_count() {

    $sends = new Send();
    return ($sends->select('id')->where_related_campaign('id',$this->id)->count());
  }
  
  public function sends_bounced() {
    $sends = new Send();
    return ($sends->select('id')->where('bounced >',0)->where_related_campaign('id',$this->id)->count());
  }

  public function sends_delivered() {
    $sends = new Send();
    return ($sends->select('id')->where('sent >',0)->where('read',0)->where('bounced',0)->where_related_campaign('id',$this->id)->count()); 
  }

  public function sends_read() {
    $sends = new Send();
    return ($sends->select('id')->where('read >',0)->where_related_campaign('id',$this->id)->count()); 
  }
  
  public function sends_undelivered() {
	  $sends = new Send();
    return ($sends->select('id')->where('tries >',1)->where('sent',0)->where('read',0)->where('bounced',0)->where_related_campaign('id',$this->id)->count()); 
  }
  
  public function delete() {

    $ci =& get_instance();

    $campaign_path = $ci->config->item('clients_path') . $this->client->slug . '/campaigns/'. $this->id;

    if (parent::delete()) {
      // workaround of deleting relationships
      $this->db->query("DELETE FROM `sends` WHERE `campaign_id` is NULL");

      // removes campaign folder
      recursive_remove_directory($campaign_path);
      return TRUE;
    }
    else
      return FALSE;
    
  } // delete 

} // Class Campaign

/* End of file campaign.php */
/* Location: ./system/application/models/campaign.php */